package com.duoec.dw.lineage.service.analyser.expr;

import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLInSubQueryExpr;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLWithSubqueryClause;
import com.duoec.dw.lineage.core.utils.AnalyserUtils;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import com.duoec.dw.lineage.dto.TableFieldDependencyDto;
import com.duoec.dw.lineage.dto.TableFieldLineageDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;

/**
 * @author xuwenzhen
 */
@Service
public class InSubQueryExpr extends BaseExprAnalyser<SQLInSubQueryExpr> {
    /**
     * 获取匹配类型
     *
     * @return 类型
     */
    @Override
    public Class<SQLInSubQueryExpr> getSqlExprType() {
        return SQLInSubQueryExpr.class;
    }

    /**
     * 分析表达式语句
     *
     * @param expr         表达式语句 where event_name in (select event_name from edw_public.dim_boss_manager_active_dot_event_name_df)
     * @param fromLineages 当前语句from解析出来的血缘关系
     * @return 此表达式抽取出来的依赖
     */
    @Override
    public LinkedHashSet<TableFieldDependencyDto> analyse(SQLInSubQueryExpr expr, MultiTableLineageDto fromLineages) {
        LinkedHashSet<TableFieldDependencyDto> dependencies = new LinkedHashSet<>();

        SQLExpr fieldExpr = expr.getExpr();
        LinkedHashSet<TableFieldDependencyDto> dependencies1 = hiveAnalyser.analyseExpr(fromLineages, fieldExpr);
        AnalyserUtils.mergeToDependencies(dependencies, dependencies1);

        SQLSelect query = expr.getSubQuery();
        TableLineageDto subQueryLineages = hiveAnalyser.analyseQuery(query.getQuery(), null);
        //TODO 处理由父级传递下来的 with-in

        LinkedHashSet<TableFieldDependencyDto> subQueryGlobalDependencies = subQueryLineages.getDependencies();
        if (subQueryGlobalDependencies != null) {
            AnalyserUtils.mergeToDependencies(dependencies, subQueryGlobalDependencies);
        }
        for (TableFieldLineageDto field : subQueryLineages.getFields()) {
            LinkedHashSet<TableFieldDependencyDto> fieldDependencies = field.getDependencies();
            if (fieldDependencies != null) {
                AnalyserUtils.mergeToDependencies(dependencies, fieldDependencies);
            }
        }

        return dependencies;
    }
}
